/**
 * 
 */
package com.huniu.utility;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * @author zandy (chenheng)
 * 
 */
public abstract class DateUtil {

	final public static String DATE_FORMAT_1 = "yyyy-MM-dd";
	final public static String DATE_FORMAT_2 = "HH-mm-ss-SSS";
	final public static long DAY_TO_MILL_SECCOND = 24 * 60 * 60 * 1000;

	public static String convertDateToString(Date date, String distFormat) {
		DateFormat dateFormat = new SimpleDateFormat(distFormat);
		return dateFormat.format(date);
	}

	public static Date convertStringToDate(String strDate, String dateFormat)
			throws ParseException {
		DateFormat format = new SimpleDateFormat(dateFormat);
		return format.parse(strDate);
	}

	public static String convertDateFormat(String originalDate,
			String sourceFormat, String destinationFormat)
			throws ParseException {
		DateFormat dateFormat = new SimpleDateFormat(sourceFormat);
		Date date = dateFormat.parse(originalDate);
		GregorianCalendar calender = new GregorianCalendar();
		calender.setTime(date);
		dateFormat = new SimpleDateFormat(destinationFormat);
		date = calender.getTime();
		return dateFormat.format(date);
	}

	public static long calculateDuration(String startDate, String endDate,
			String startDateFormat, String endDateFormat) throws ParseException {
		DateFormat format = new SimpleDateFormat(DATE_FORMAT_1);
		long startDateTime = format.parse(
				startDateFormat.equals(DATE_FORMAT_1) ? startDate
						: convertDateFormat(startDate, startDateFormat,
								DATE_FORMAT_1)).getTime();
		long endDateTime = format.parse(
				endDateFormat.equals(DATE_FORMAT_1) ? endDate
						: convertDateFormat(endDate, endDateFormat,
								DATE_FORMAT_1)).getTime();
		long durationTime = Math.abs(endDateTime - startDateTime);
		return (durationTime / DAY_TO_MILL_SECCOND);
	}

}
